<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>AI易经出行 v4.1.1 - 移动端版</title>
    <style>
        /* 移动端优化样式 */
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --accent-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --text-light: #ecf0f1;
            --shadow: 0 4px 20px rgba(0,0,0,0.3);
            --border-radius: 12px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--primary-gradient);
            color: var(--text-light);
            min-height: 100vh;
            overflow-x: hidden;
            touch-action: manipulation;
        }

        .container {
            max-width: 100%;
            padding: 10px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 头部区域 */
        .header {
            text-align: center;
            padding: 20px 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            margin-bottom: 15px;
        }

        .header h1 {
            font-size: 1.8rem;
            font-weight: 300;
            margin-bottom: 5px;
            background: var(--accent-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header p {
            font-size: 0.9rem;
            opacity: 0.8;
        }

        /* 时间信息卡片 */
        .time-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: var(--shadow);
        }

        .time-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }

        .time-item {
            text-align: center;
            padding: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
        }

        .time-label {
            font-size: 0.8rem;
            opacity: 0.7;
            margin-bottom: 5px;
        }

        .time-value {
            font-size: 1rem;
            font-weight: 600;
        }

        /* 移动端方向按钮网格 */
        .direction-container {
            display: flex;
            justify-content: center;
            margin: 20px 0;
            padding: 0 10px;
        }

        .direction-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-template-rows: repeat(2, 1fr);
            gap: 12px;
            width: 100%;
            max-width: 320px;
        }

        .direction-btn {
            aspect-ratio: 1;
            min-height: 70px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.1rem;
            font-weight: bold;
            color: var(--text-light);
            cursor: pointer;
            transition: var(--transition);
            touch-action: manipulation;
            position: relative;
            overflow: hidden;
        }

        .direction-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%);
            transform: translateX(-100%);
            transition: transform 0.6s;
        }

        .direction-btn:active {
            transform: scale(0.95);
            background: rgba(255, 255, 255, 0.2);
        }

        .direction-btn:active::before {
            transform: translateX(100%);
        }

        .direction-btn.active {
            background: var(--accent-gradient);
            border-color: rgba(255, 255, 255, 0.4);
            box-shadow: 0 0 20px rgba(79, 172, 254, 0.3);
        }

        /* 方向按钮颜色主题 */
        .direction-btn[data-direction="北"] {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
        }
        .direction-btn[data-direction="东北"] {
            background: linear-gradient(135deg, #f39c12, #e67e22);
        }
        .direction-btn[data-direction="东"] {
            background: linear-gradient(135deg, #27ae60, #229954);
        }
        .direction-btn[data-direction="东南"] {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
        }
        .direction-btn[data-direction="南"] {
            background: linear-gradient(135deg, #3498db, #2980b9);
        }
        .direction-btn[data-direction="西南"] {
            background: linear-gradient(135deg, #9b59b6, #8e44ad);
        }
        .direction-btn[data-direction="西"] {
            background: linear-gradient(135deg, #e91e63, #c2185b);
        }
        .direction-btn[data-direction="西北"] {
            background: linear-gradient(135deg, #ff6b6b, #e74c3c);
        }

        /* 选中状态覆盖 */
        .direction-btn.active {
            background: var(--accent-gradient) !important;
            color: white;
            transform: scale(1.05);
        }

        /* 结果显示区域 */
        .result-container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 20px;
            margin: 20px 0;
            box-shadow: var(--shadow);
            display: none;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
        }

        .direction-title {
            font-size: 1.4rem;
            font-weight: 600;
        }

        .jx-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 1rem;
            min-width: 60px;
            text-align: center;
        }

        .jx-badge.ji {
            background: var(--success-color);
            color: white;
        }

        .jx-badge.xiong {
            background: var(--danger-color);
            color: white;
        }

        .result-content {
            margin: 15px 0;
            line-height: 1.6;
            font-size: 1rem;
        }

        .jie-method {
            margin-top: 15px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }

        .jie-method h4 {
            margin-bottom: 8px;
            color: #3498db;
        }

        /* 功能区 */
        .function-area {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 20px;
            margin: 20px 0;
            box-shadow: var(--shadow);
        }

        .input-group {
            margin-bottom: 15px;
        }

        .input-label {
            font-size: 1rem;
            margin-bottom: 10px;
            display: block;
        }

        .input-row {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        input[type="text"] {
            width: 100%;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            color: var(--text-light);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            font-size: 1rem;
            transition: var(--transition);
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 20px rgba(52, 152, 219, 0.3);
        }

        input[type="text"]::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        button {
            padding: 15px 20px;
            background: var(--accent-gradient);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: var(--transition);
            box-shadow: var(--shadow);
            touch-action: manipulation;
        }

        button:active {
            transform: scale(0.98);
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .button-row {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-top: 15px;
        }

        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 30px;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 触摸反馈 */
        .touch-feedback {
            position: relative;
            overflow: hidden;
        }

        .touch-feedback::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.3s, height 0.3s;
        }

        .touch-feedback:active::before {
            width: 200px;
            height: 200px;
        }

        /* 响应式调整 */
        @media (max-width: 480px) {
            .direction-grid {
                max-width: 280px;
                gap: 10px;
            }
            
            .direction-btn {
                min-height: 60px;
                font-size: 1rem;
            }
        }

        @media (max-width: 360px) {
            .direction-grid {
                max-width: 260px;
                gap: 8px;
            }
            
            .direction-btn {
                min-height: 55px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <h1>AI易经出行 v4.1.1</h1>
            <p>移动端智能运势分析</p>
        </div>

        <!-- 时间信息 -->
        <div class="time-card">
            <div class="time-grid">
                <div class="time-item">
                    <div class="time-label">当前时间</div>
                    <div id="current-time" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">农历时辰</div>
                    <div id="shi-chen" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">黄道信息</div>
                    <div id="huang-dao" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">能量等级</div>
                    <div id="energy-level" class="time-value">-</div>
                </div>
            </div>
        </div>

        <!-- 移动端方向按钮网格 -->
        <div class="direction-container">
            <div class="direction-grid">
                <button class="direction-btn touch-feedback" data-direction="北">北</button>
                <button class="direction-btn touch-feedback" data-direction="东北">东北</button>
                <button class="direction-btn touch-feedback" data-direction="东">东</button>
                <button class="direction-btn touch-feedback" data-direction="东南">东南</button>
                <button class="direction-btn touch-feedback" data-direction="西">西</button>
                <button class="direction-btn touch-feedback" data-direction="西北">西北</button>
                <button class="direction-btn touch-feedback" data-direction="南">南</button>
                <button class="direction-btn touch-feedback" data-direction="西南">西南</button>
            </div>
        </div>

        <!-- 结果显示区域 -->
        <div class="result-container" id="result-container">
            <div class="result-header">
                <div class="direction-title">方向: <span id="selected-direction">-</span></div>
                <div id="jx-badge" class="jx-badge">-</div>
            </div>
            <div id="result-content" class="result-content">
                请选择一个方向查看吉凶信息
            </div>
            <div class="jie-method">
                <h4>解挂方法</h4>
                <div id="jie-method">-</div>
            </div>
        </div>

        <!-- 功能区 -->
        <div class="function-area">
            <div class="input-group">
                <label class="input-label">个人信息分析</label>
                <div class="input-row">
                    <input type="text" id="info-input" placeholder="姓名、生日、联系方式等">
                    <button id="analyze-btn" class="touch-feedback">开始分析</button>
                </div>
            </div>
            <div class="button-row">
                <button id="refresh-btn" class="touch-feedback" onclick="refreshData()">刷新数据</button>
                <button id="clear-cache-btn" class="touch-feedback" onclick="clearCache()">清除缓存</button>
            </div>
        </div>
    </div>

    <script>
        // 移动端优化的API服务类
        class MobileApiService {
            static CACHE_DURATION = 5 * 60 * 1000;
            static cache = new Map();
            static API_CONFIG = {
                baseUrl: "https://api.siliconflow.cn/v1/chat/completions",
                model: "Qwen/Qwen2.5-7B-Instruct",
                timeout: 20000,
                retryCount: 2
            };

            static async callAiYiJingApi(info, options = {}) {
                const cacheKey = this._generateCacheKey(info, options);
                
                if (this.cache.has(cacheKey)) {
                    const cached = this.cache.get(cacheKey);
                    if (Date.now() - cached.timestamp < this.CACHE_DURATION) {
                        return cached.data;
                    }
                }

                const content_text = this._generatePrompt(info);
                
                const requestOptions = {
                    method: "POST",
                    headers: {
                        Authorization: "Bearer sk-xziuakupoderrivcjtmpirqodwtasvnddhjmfwetquulqwbi",
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        messages: [{ content: content_text, role: "user" }],
                        model: this.API_CONFIG.model,
                        temperature: 0.7,
                        max_tokens: 800
                    }),
                };
                
                return this._callWithRetry(requestOptions, cacheKey);
            }

            static async _callWithRetry(requestOptions, cacheKey) {
                let lastError;
                
                for (let i = 0; i < this.API_CONFIG.retryCount; i++) {
                    try {
                        const controller = new AbortController();
                        const timeoutId = setTimeout(() => controller.abort(), this.API_CONFIG.timeout);
                        
                        const response = await fetch(this.API_CONFIG.baseUrl, {
                            ...requestOptions,
                            signal: controller.signal
                        });
                        
                        clearTimeout(timeoutId);
                        
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }
                        
                        const data = await response.json();
                        const result = this._parseResponse(data);
                        
                        this.cache.set(cacheKey, {
                            data: result,
                            timestamp: Date.now()
                        });
                        
                        return result;
                        
                    } catch (error) {
                        lastError = error;
                        if (i < this.API_CONFIG.retryCount - 1) {
                            await new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    }
                }
                
                throw new Error(`API调用失败: ${lastError.message}`);
            }

            static _parseResponse(response) {
                try {
                    const content = response.choices[0].message.content;
                    const parsed = JSON.parse(content);
                    
                    if (!parsed.today_luck || !parsed.jx || !parsed.info) {
                        throw new Error("API返回数据格式不完整");
                    }
                    
                    return { ...parsed, timestamp: Date.now(), version: "4.1.1" };
                } catch (error) {
                    throw new Error("API返回数据格式错误");
                }
            }

            static _generatePrompt(info) {
                return `请你扮演一位精通易学的老师，根据我提供的信息推算运势以及出行八个方向的吉凶情况。
推算步骤：
1、先根据给出的日期进行当日黄道信息的获取
2、再根据给出的方向进行当日的吉凶判断
3、最后根据具体方向的吉凶说明具体的运势方向信息，如果是不吉利的需要给出解挂的方法
推算结果仅返回运势以及方位的吉凶信息，以 JSON 格式呈现，格式如下：
{
    "today_luck": "今日运势",
    "jx": "吉凶",
    "info": "具体运势",
    "jie": "解挂方法"
}
本次我给你的信息是：${info}`;
            }

            static _generateCacheKey(info, options) {
                return btoa(JSON.stringify({ info, options }));
            }

            static clearCache() {
                this.cache.clear();
            }
        }

        // 全局变量
        window.currentDirection = "";
        window.apiResult = null;
        window.needleRotation = 0;

        // 方向到角度的映射
        const directionAngles = {
            '北': 0, '东北': 45, '东': 90, '东南': 135,
            '南': 180, '西南': 225, '西': 270, '西北': 315
        };

        // 移动端优化的时间函数
        function getCurrentTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        function convertToChineseTime(hour, minute) {
            const times = ['子时', '丑时', '寅时', '卯时', '辰时', '巳时', '午时', '未时', '申时', '酉时', '戌时', '亥时'];
            const timeIndex = Math.floor((hour + 1) / 2) % 12;
            const minuteMark = minute < 15 ? '一刻' : minute < 30 ? '二刻' : minute < 45 ? '三刻' : '四刻';
            return `${times[timeIndex]}${minuteMark}`;
        }

        function getHuangDaoInfo(date) {
            const day = date.getDate();
            const month = date.getMonth() + 1;
            const sum = day + month;
            return [1, 3, 5, 7, 9, 11, 13].includes(sum % 14) ? "黄道吉日" : "黑道凶日";
        }

        function calculateEnergyLevel(hour, minute) {
            const baseEnergy = 50;
            const timeBonus = Math.sin((hour + minute / 60) * Math.PI / 12) * 30;
            const randomFactor = Math.random() * 20;
            return Math.max(0, Math.min(100, Math.round(baseEnergy + timeBonus + randomFactor)));
        }

        function updateTimeInfo() {
            const currentTime = getCurrentTime();
            const now = new Date();
            const hour = now.getHours();
            const minute = now.getMinutes();
            
            document.getElementById('current-time').textContent = currentTime;
            document.getElementById('shi-chen').textContent = convertToChineseTime(hour, minute);
            document.getElementById('huang-dao').textContent = getHuangDaoInfo(now);
            
            const energyLevel = calculateEnergyLevel(hour, minute);
            document.getElementById('energy-level').textContent = `${energyLevel}%`;
            
            return { currentTime, energyLevel };
        }

        function selectDirection(direction) {
            // 移除所有按钮的active状态
            document.querySelectorAll('.direction-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 为选中的按钮添加active状态
            const selectedBtn = document.querySelector(`[data-direction="${direction}"]`);
            if (selectedBtn) {
                selectedBtn.classList.add('active');
            }
            
            console.log(`选择方向: ${direction}`);
        }

        function updateResultDisplay() {
            if (!window.apiResult || !window.currentDirection) return;
            
            const result = window.apiResult;
            document.getElementById('selected-direction').textContent = window.currentDirection;
            
            const jxBadge = document.getElementById('jx-badge');
            jxBadge.textContent = result.jx || '-';
            jxBadge.className = 'jx-badge';
            if (result.jx === "吉") {
                jxBadge.classList.add('ji');
            } else if (result.jx === "凶") {
                jxBadge.classList.add('xiong');
            }
            
            document.getElementById('result-content').textContent = result.info || '无详细信息';
            document.getElementById('jie-method').textContent = result.jie || '-';
            
            document.getElementById('result-container').style.display = 'block';
        }

        function generateMockResult(direction, energyLevel) {
            const mockResults = {
                '东': { jx: '吉', info: '东方为木，生机勃勃，适合出行，事业顺利', jie: '佩戴绿色饰品，选择绿色出行工具' },
                '南': { jx: '吉', info: '南方为火，热情似火，人际关系佳，财运亨通', jie: '穿着红色衣物，选择红色装饰' },
                '西': { jx: '凶', info: '西方为金，今日金气过旺，易有口舌是非', jie: '避免白色物品，佩戴黄色饰品化解' },
                '北': { jx: '吉', info: '北方为水，智慧如海，学习工作顺利', jie: '多接触蓝色物品，保持冷静' },
                '东南': { jx: '吉', info: '东南为巽，风调雨顺，财运亨通', jie: '选择绿色或蓝色装饰' },
                '东北': { jx: '凶', info: '东北为艮，山重水复，阻碍较多', jie: '避免黄色物品，选择红色化解' },
                '西南': { jx: '吉', info: '西南为坤，厚德载物，家庭和睦', jie: '多接触黄色物品，保持平和心态' },
                '西北': { jx: '凶', info: '西北为乾，刚强过甚，易有冲突', jie: '避免金属物品，选择绿色调和' }
            };
            
            const baseResult = mockResults[direction] || { jx: '中', info: '此方向运势平稳', jie: '保持平常心即可' };
            
            return {
                today_luck: `今日${direction}方运势${baseResult.jx === '吉' ? '大吉' : baseResult.jx === '凶' ? '不利' : '平稳'}`,
                jx: baseResult.jx,
                info: baseResult.info,
                jie: baseResult.jie,
                energy_level: energyLevel
            };
        }

        function lockUI() {
            document.querySelectorAll('button, input').forEach(el => {
                el.disabled = true;
            });
            
            const resultContent = document.getElementById('result-content');
            resultContent.innerHTML = '<div class="loading"><div class="spinner"></div><div style="margin-left: 15px;">正在分析中...</div></div>';
        }

        function unlockUI() {
            document.querySelectorAll('button, input').forEach(el => {
                el.disabled = false;
            });
        }

        window.aiYiJingChuXing = async function(userInfo, direction) {
            try {
                lockUI();
                
                const timeInfo = updateTimeInfo();
                const info = userInfo 
                    ? `${userInfo}，方向：${direction}，当前时间：${timeInfo.currentTime}` 
                    : `方向：${direction}，当前时间：${timeInfo.currentTime}`;
                
                try {
                    const result = await MobileApiService.callAiYiJingApi(info);
                    window.apiResult = result;
                } catch (apiError) {
                    window.apiResult = generateMockResult(direction, timeInfo.energyLevel);
                }
                
                window.currentDirection = direction;
                updateResultDisplay();
                
            } catch (error) {
                console.error("分析失败:", error);
                alert("分析失败，请稍后再试");
            } finally {
                unlockUI();
            }
        };

        window.refreshData = function() {
            if (window.currentDirection) {
                const userInfo = document.getElementById('info-input').value;
                aiYiJingChuXing(userInfo, window.currentDirection);
            } else {
                alert("请先选择一个方向");
            }
        };

        window.clearCache = function() {
            MobileApiService.clearCache();
            alert("缓存已清除");
        };

        // 移动端触摸事件处理
        function addTouchEvents() {
            const directionBtns = document.querySelectorAll('.direction-btn');
            
            directionBtns.forEach(btn => {
                // 触摸开始
                btn.addEventListener('touchstart', function(e) {
                    e.preventDefault();
                    this.style.transform = 'scale(0.95)';
                }, { passive: false });
                
                // 触摸结束
                btn.addEventListener('touchend', function(e) {
                    e.preventDefault();
                    this.style.transform = 'scale(1)';
                    
                    const direction = this.getAttribute('data-direction');
                    window.currentDirection = direction;
                    selectDirection(direction);
                    
                    const userInfo = document.getElementById('info-input').value;
                    aiYiJingChuXing(userInfo, direction);
                }, { passive: false });
                
                // 点击事件（备用）
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const direction = this.getAttribute('data-direction');
                    window.currentDirection = direction;
                    selectDirection(direction);
                    
                    const userInfo = document.getElementById('info-input').value;
                    aiYiJingChuXing(userInfo, direction);
                });
            });
        }

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateTimeInfo();
            setInterval(updateTimeInfo, 60000);
            
            // 添加触摸事件
            addTouchEvents();
            
            // 分析按钮事件
            const analyzeBtn = document.getElementById('analyze-btn');
            if (analyzeBtn) {
                analyzeBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (window.currentDirection) {
                        const userInfo = document.getElementById('info-input').value;
                        aiYiJingChuXing(userInfo, window.currentDirection);
                    } else {
                        alert("请先选择一个方向");
                    }
                });
            }
        });
    </script>
</body>
</html>
